package com.km.wskj.itmonitor.pager.wq.wscollege;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.CollegeItem;
import com.km.wskj.itmonitor.model.KnowledgeLibrary;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;


/**
 * @author by Xianling.Zhou on 2017/2/9.
 */
public class CollegeListActivity extends LActivity implements StateLayout.OnViewRefreshListener {

    private static final String TAG = "CollegeListActivity";
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    KnowledgeLibrary mKnowledgeLibrary;
    private MyAdapter mAdapter;
    private int pageIndex;
    private int lastUpdateNum;
    private List<CollegeItem> mCollegeLists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_college_list);
        ButterKnife.bind(this);

        if (getIntent().hasExtra("data")) {
            mKnowledgeLibrary = (KnowledgeLibrary) getIntent().getSerializableExtra("data");
            toolBarTitle.setText(mKnowledgeLibrary.columnName);
        }

        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRight.setVisibility(View.VISIBLE);
        toolBarRight.setImageResource(R.mipmap.search_white);

        initData();
    }

    private void initData() {
        stateLayout.showLoadingView();
        pdc.collegeList(HTTP_TASK_TAG, mKnowledgeLibrary.id, 1, Constant.PageListSize, new ZxlGenericsCallback<List<CollegeItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<CollegeItem> collegeLists, int i) {
                if (collegeLists.size() == 0)
                    stateLayout.showEmptyView();

                mCollegeLists = collegeLists;
                lastUpdateNum = collegeLists.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });

        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#f1f1f1"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                CollegeItem item = (CollegeItem) parent.getItemAtPosition(position);
                Intent t = new Intent(context, CollegeDetailActivity.class);
                t.putExtra("data", item);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);

        stateLayout.showContentView();
    }

    private void onRefresh() {
        pdc.collegeList(HTTP_TASK_TAG, mKnowledgeLibrary.id, 1, Constant.PageListSize
                , new ZxlGenericsCallback<List<CollegeItem>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                        stateLayout.showErrorView();
                    }

                    @Override
                    public void onResponse(List<CollegeItem> collegeLists, int i) {
                        if (collegeLists.size() == 0)
                            stateLayout.showEmptyView();
                        mCollegeLists = collegeLists;
                        lastUpdateNum = collegeLists.size();
                        pageIndex = 1;
                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setRefreshSuccess();

                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });
    }

    private void onLoadMore() {
        pdc.collegeList(HTTP_TASK_TAG, mKnowledgeLibrary.id, pageIndex + 1, Constant.PageListSize
                , new ZxlGenericsCallback<List<CollegeItem>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                        stateLayout.showErrorView();
                    }

                    @Override
                    public void onResponse(List<CollegeItem> collegeLists, int i) {
                        lastUpdateNum = collegeLists.size();
                        if (collegeLists.size() > 0) {
                            mCollegeLists.addAll(collegeLists);
                            pageIndex++;
                        }
                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setLoadMoreSuccess();
                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();

                    }
                });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right:
                normalToasty("search");
                break;
        }
    }

    //点击重试
    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mCollegeLists == null) {
                return 0;
            }
            return mCollegeLists.size();
        }

        @Override
        public Object getItem(int position) {
            return mCollegeLists.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context,
                    convertView, parent, R.layout.item_college_list);
            CollegeItem item = mCollegeLists.get(position);
            helper.setText(R.id.tv_title, item.title);
            helper.setText(R.id.tv_des, item.desc);
            helper.setText(R.id.tv_create_time, item.createTime);

            //图片url
            CollegeItem.CoverImgBean coverImg = item.coverImg;
            if (coverImg != null) {
                String url = coverImg.host + coverImg.filePath + coverImg.newFileName;
                Glide.with((Activity) context)
                        .load(url)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_preview, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }
            return helper.getView();
        }
    }
}
